/*
 * JVM_StackFrame.c
 *
 *  Created on: 03.01.2011
 *      Author: Tavin
 */

#include <String.h>
#include <stdio.h>
#include <stdlib.h>

#include "JVM_StatusCodes.h"

#include "JVM_StackFrame.h"

#include "Console.h"

/****************************************************************************************/
/*																						*/
/*	Function : JVM_StackFrame_new							Author : OG					*/
/*																						*/
/*	Description : 								   										*/
/*																						*/
/*	Version : 1.0					Date :2011.1.3			Status : Working   			*/
/*																						*/
/****************************************************************************************/


JVM_StackFrame_t * JVM_StackFrame_new(JVM_CP_Table_t *myTable, JVM_Method_t * myMethod)
{
	JVM_StackFrame_t * myStackFrame;
	uint16_t frameMemorySize;
	uint16_t fieldsCount;

	fieldsCount=myMethod->maxLocals;
	fieldsCount+=myMethod->maxStacks;

	frameMemorySize=fieldsCount<<2;

	if ((fieldsCount & 0x1)>0)
		fieldsCount++;

	frameMemorySize+=fieldsCount;
	frameMemorySize+=sizeof(JVM_StackFrame_t);

	myStackFrame=malloc(frameMemorySize);

	if (myStackFrame==NULL)
		return(NULL);


	myStackFrame->stackPointer=0;
	myStackFrame->variablePointer=myMethod->maxStacks;
	myStackFrame->typePointer=myMethod->maxStacks+myMethod->maxLocals;

	myStackFrame->PC=0;
	myStackFrame->previus=NULL;
	myStackFrame->currentCpTable=myTable;
	myStackFrame->currentMethod=myMethod;

	return(myStackFrame);

}

/****************************************************************************************/
/*																						*/
/*	Function : JVM_StackFrame_destroy						Author : OG					*/
/*																						*/
/*	Description : 								   										*/
/*																						*/
/*	Version : 1.0					Date :2011.1.5			Status : Working   			*/
/*																						*/
/****************************************************************************************/


uint16_t JVM_StackFrame_destroy(JVM_StackFrame_t *myStackFrame )
{
	free(myStackFrame);

	return(STCD_OK);

}

uint16_t JVM_Stack_unroll(JVM_StackFrame_t *myStackFrame) {

	JVM_StackFrame_t *current = myStackFrame;

	while(current !=  NULL) {
		JVM_StackFrame_destroy(current);
		// TODO: handle other stuff here
		current = myStackFrame->previus;
	}

	return(STCD_OK);
}
